//
//  PublishViewController.m
//  LeDiao
//
//  Created by 千金贷 on 16/3/8.
//  Copyright © 2016年 xuxuan. All rights reserved.
//

#import "PublishViewController.h"
#import "UploadCell.h"
#import "ELCImagePickerController.h"

#import <MobileCoreServices/UTCoreTypes.h> 
#import <AssetsLibrary/AssetsLibrary.h>
#import "AFNetworking.h"
#import "AFHTTPRequestOperationManager.h"

#import "SJAvatarBrowser.h"

#import "XHud.h"


@interface PublishViewController ()<UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,ELCImagePickerControllerDelegate>
{
    NSString *city;
    NSString *province;
    
    NSString *bankuaiNumber;
    
    
    MBProgressHUD *_hud;
}
@property (nonatomic, assign) NSInteger index;

@end

@implementation PublishViewController

- (id)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        self.title = @"发帖";
        _imagePaths = [[NSMutableArray alloc] init];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setUpForDismissKeyboard];
    
    _hud = [XHud createHUDInwindow];
    
    province = @"";
    city     = @"";
    
    bankuaiNumber = @"";
    
    self.view.backgroundColor = WhiteColor;
    


    UIBarButtonItem * right = [[UIBarButtonItem alloc]initWithTitle: @"发表" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClick)];
    right.tintColor = WhiteColor;
    self.navigationItem.rightBarButtonItem = right;
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(68, 68);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 5; //上下的间距 可以设置0看下效果
    layout.sectionInset = UIEdgeInsetsMake(0.f, 0, 9.f, 0);
    [_imageCollection registerNib:[UINib nibWithNibName:@"UploadCell" bundle:nil] forCellWithReuseIdentifier:@"UploadCell"];
    _imageCollection.delegate = self;
    _imageCollection.dataSource =self; 

    
}


#pragma mark - textview delegate
- (void)textViewDidChange:(UITextView *)textView
{
    
    if ([textView.text isEqualToString:@""]) {
        _placehoder.hidden = NO;
    }else _placehoder.hidden = YES;
    if (textView.text.length > 500) {
        NSMutableString *str = [textView.text mutableCopy];
        [str deleteCharactersInRange:NSMakeRange(500, textView.text.length - 500)];
        textView.text = str;
    }

}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if (![text isEqualToString:@""])
    {
        _placehoder.hidden = YES;
    }
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)
    {
        _placehoder.hidden = NO;
    }
    if (textView.text.length > 500) {
        NSMutableString *str = [textView.text mutableCopy];
        [str deleteCharactersInRange:NSMakeRange(500, textView.text.length - 500)];
        textView.text = str;
    }
    return YES;
    
}
//实现弹出键盘时，输入框上移至不被隐藏
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (kScreenHeight < 500) {
        
        CGFloat offset = -50;
        
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame=self.view.frame;
            frame.origin.y=offset;
            self.view.frame=frame;
        }];
    }
    return YES;
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect frame=self.view.frame;
        frame.origin.y=64;
        self.view.frame=frame;
    }];
    
    return YES;
}




#pragma mark - 发表按钮
- (void)rightButtonClick
{
    [self.view endEditing:YES];
    _hud = nil;
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.labelFont = [UIFont systemFontOfSize:12.0f];

    [self.view addSubview:_hud];
    _hud.mode = MBProgressHUDModeText;
    _hud.dimBackground = NO;
    _hud.labelText = @"请选择地区";

    //    去除两端空格和回车
    _textView.text = [_textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([province isEqualToString:@""]) {
        _hud.labelText = @"请选择地区";
        [_hud show:YES];
        [_hud hide:YES afterDelay:0.7];
//        [XHud showHud:_hud WithTipText:@"请选择地区"];
//        [XHud showHud:_hud WithWaitigText:@"请选择地区"];

    }else
    
    if ([bankuaiNumber isEqualToString:@""]) {
//        [XHud showHud:_hud WithTipText:@"请选择发表板块"];
        _hud.labelText = @"请选择发表板块";
        [_hud show:YES];

        [_hud hide:YES afterDelay:0.7];


    }else
    if ([_textView.text isEqualToString:@""]) {
//        [XHud showHud:_hud WithTipText:@"请输入帖子内容"];


        _hud.labelText = @"请输入帖子内容";
        [_hud show:YES];

        [_hud hide:YES afterDelay:0.7];


    }else{
        _hud.mode = MBProgressHUDModeIndeterminate;
        _hud.dimBackground = YES;
        
        _hud.labelText = @"正在提交，请稍候";
        [_hud show:YES];
        
//        对应版块和编号
        NSInteger bankuai = [bankuaiNumber integerValue];
        NSNumber *bkN;
        switch (bankuai) {
            case 1:
                bkN = @1;
                break;
                
            case 2:
                bkN = @7;
                break;
                
            case 3:
                bkN = @2;
                break;
                
            case 4:
                bkN = @3;
                break;
                
            case 5:
                bkN = @4;
                break;
                
                
            case 6:
                bkN = @5;
                break;
                
            case 7:
                bkN = @6;
                break;
                
            default:
                break;
        }

        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        NSString *url = [BaseURL stringByAppendingString:@"world/addPost"];
        NSLog(@"url = %@",url);
        
        NSString *fileName = @"";
        
        NSString *timeInterval = [NSString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];
        if (_imagePaths.count > 0) {
            
            for (int i = 0; i < _imagePaths.count; i ++) {
                fileName = [fileName stringByAppendingString:[NSString stringWithFormat:@"/attachFiles/%@/world/pindiao_%@%@00%d.png,",GetmemberNum,GetmemberNum,timeInterval,i]];
            }
            
            fileName = [fileName substringToIndex:fileName.length - 1];
            
        }
        
        
        NSLog(@"%@",fileName);
        
        NSDictionary*dic=@{@"forumplate":bkN,
                           @"memberid":Getmemberid,
                           @"title":@"",
                           @"content":_textView.text,
                           @"city":city,
                           @"province":province,
                           @"pic":fileName};
        //
        
        NSLog(@"%@",dic);
        NSLog(@"%@",_imagePaths);
        
        AFHTTPRequestOperation *op;
        if (_imagePaths.count > 0) {
            
            //        有图片时上传图片
            op = [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                
                if (_imagePaths.count > 0) {
                    
                    for (int i = 0; i < _imagePaths.count; i ++) {
                        
                        UIImage *image = _imagePaths[i];
                        UIImage *newImage = [self compressImage:image];
                        NSData *imageData = UIImagePNGRepresentation(newImage);
                        // 上传图片，以文件流的格式
                        
                        NSString *imageName = [NSString stringWithFormat:@"/attachFiles/%@/world/pindiao_%@%@00%d.png",GetmemberNum,GetmemberNum,timeInterval,i];
                        
                        
                        //@"/attachFiles/60014/world/pindiao_600141458000221777.png";
                        
                        [formData appendPartWithFileData:imageData name:@"File" fileName:imageName mimeType:@"image/png"];
                        
                    }
                    
                }
                
                
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                //             _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;
                
                
                NSError*error;
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                if (dic == nil) {
                    NSString*str=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                    NSLog(@"失败,返回数据为空%@",str);
                    //                    [XHud showHud:_hud WithTipText:@"发表失败"];
                    _hud.mode = MBProgressHUDModeText;
                    _hud.dimBackground = NO;
                    _hud.labelText = @"发表失败";
                    [_hud show:YES];
                    [_hud hide:YES afterDelay:0.7];
                    
                }
                else{
                    //po
                    if ([[dic valueForKey:@"code"] integerValue] == 4000) {
                        NSLog(@"成功状态%@",dic);
                        
                        //                        [XHud showHud:_hud WithTipText:@"发表成功"];
                        _hud.mode = MBProgressHUDModeText;
                        _hud.dimBackground = NO;
                        _hud.labelText = @"发表成功";
                        [_hud show:YES];
                        [_hud hide:YES afterDelay:0.7];
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        NSLog(@"返回失败状态%@",dic);
                        if ([[dic valueForKey:@"code"] isEqualToString:@"3001"]) {
                            [[[UIAlertView alloc] initWithTitle:@"发表失败" message:@"只有厂商认证用户才能发帖到发现板块"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil] show];
                            [_hud hide:YES];
                            
                        }else{
                            
                            //                        [XHud showHud:_hud WithTipText:@"发表失败"];
                            _hud.mode = MBProgressHUDModeText;
                            _hud.dimBackground = NO;
                            _hud.labelText = @"发表失败";
                            [_hud show:YES];
                            [_hud hide:YES afterDelay:0.7];
                            
                        }
                    }
                    
                    
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;
                NSLog(@"%@",error.localizedDescription);
//                [XHud showHud:_hud WithTipText:@"发表失败"];
                _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;
                _hud.labelText = @"发表失败";
                [_hud show:YES];
                [_hud hide:YES afterDelay:0.7];

            }];
            
        }else{
            
            //        无图片，只传文字
            op=[manager POST:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;


                NSError*error;
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
                if (dic == nil) {
                    NSString*str=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                    NSLog(@"失败,返回数据为空%@",str);
//                    [XHud showHud:_hud WithTipText:@"发表失败"];
                    _hud.mode = MBProgressHUDModeText;
                    _hud.dimBackground = NO;
                    _hud.labelText = @"发表失败";
                    [_hud show:YES];
                    [_hud hide:YES afterDelay:0.7];

                }
                else{
                    //po
                    if ([[dic valueForKey:@"code"] integerValue] == 4000) {
                        NSLog(@"成功状态%@",dic);
                        
//                        [XHud showHud:_hud WithTipText:@"发表成功"];
                        _hud.mode = MBProgressHUDModeText;
                        _hud.dimBackground = NO;
                        _hud.labelText = @"发表成功";
                        [_hud show:YES];
                        [_hud hide:YES afterDelay:0.7];

                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        NSLog(@"返回失败状态%@",dic);
                        if ([[dic valueForKey:@"code"] isEqualToString:@"3001"]) {
                            [[[UIAlertView alloc] initWithTitle:@"发表失败" message:@"只有厂商认证用户才能发帖到发现板块"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil] show];
                            [_hud hide:YES];
                            
                        }else{
                            
                            //                        [XHud showHud:_hud WithTipText:@"发表失败"];
                            _hud.mode = MBProgressHUDModeText;
                            _hud.dimBackground = NO;
                            _hud.labelText = @"发表失败";
                            [_hud show:YES];
                            [_hud hide:YES afterDelay:0.7];
                            
                        }
                    }
                    
                    
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;
                _hud.mode = MBProgressHUDModeText;
                _hud.dimBackground = NO;
                _hud.labelText = @"发表失败";
                [_hud show:YES];
                [_hud hide:YES afterDelay:0.7];

                NSLog(@"请求失败，error = %@",error.localizedDescription);
//                [XHud showHud:_hud WithTipText:@"发表失败"];
                
            }];
            
        }
        //
        op.responseSerializer = [AFCompoundResponseSerializer serializer];
        [op start];
        
    }
    

}




#pragma mark - UICollectionViewDelegateFlowLayout

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 0, 0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(68, 68);
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_imagePaths.count == 9) {
        return 9;
    }
    return [self.imagePaths count]+1;//比全局集合多一个模块
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UploadCell * cell;
    cell =  (UploadCell *)[_imageCollection dequeueReusableCellWithReuseIdentifier:@"UploadCell" forIndexPath:indexPath];
    //    cell.tag  = _flag;
    //    _flag++;
    if((long)indexPath.row!=[_imagePaths count]){//如果表格的序号不等于image集合的最大长度
        //        NSString *image = [_imagePaths objectAtIndex:indexPath.row]; //生产一个应用模块
        //        [cell.image sd_setImageWithURL:[NSURL URLWithString:image]];
        // [cell.image setImage:imageView.image];
        cell.image.image = _imagePaths[indexPath.row];
        cell.xbtn.tag = indexPath.row + 200;
        cell.tag = indexPath.row + 300;
        cell.xbtn.hidden = NO;
        [cell.xbtn addTarget:self action:@selector(xCell:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell.image.image = [UIImage imageNamed:@"shangchuanrenzheng"];
        cell.xbtn.hidden = YES;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UploadCell *cell =(UploadCell * ) [collectionView cellForItemAtIndexPath:indexPath];
    if((long)indexPath.row==[_imagePaths count]){//如果表格的序号 等于image集合的最大长度
        [self choseButtonClicked];
        
    }else{
        if (cell.image.image!=nil) {
            [SJAvatarBrowser showImage:cell.image];//调用方法
        }
        return;
    }
    
}
-(void)xCell:(UIButton *)btn{
    //取出点击的cell
    
    UploadCell *c = (UploadCell * )[[btn superview] superview];//[_imageCollection viewWithTag:btn.tag + 100];
    NSIndexPath *ffIndexPath = [_imageCollection indexPathForCell:c];
    NSUInteger didPosition = ffIndexPath.row;
//    NSUInteger didPosition = btn.tag - 200;
    
    
    if (didPosition >= _imagePaths.count) {
//        保证删除数据时不会因为越界而崩溃
        NSLog(@"越界");
        [_imageCollection reloadData];
        return;
    }
    [_imagePaths removeObjectAtIndex:didPosition];
//    NSLog(@"%d",_imagePaths.count);
    
    if (_imagePaths.count == 8) {
        [_imageCollection reloadData];
        return;
    }
    
    NSMutableArray *indexPathArray = [NSMutableArray array];
    NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:didPosition inSection:0];
//    NSLog(@"%@",tempIndexPath);
    [indexPathArray addObject:tempIndexPath];
    [_imageCollection deleteItemsAtIndexPaths:indexPathArray];
    [_imageCollection reloadData];
}

- (void)choseButtonClicked
{
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    
    elcPicker.maximumImagesCount = 9 - _imagePaths.count; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie]; //Supports image and movie types
    
    elcPicker.imagePickerDelegate = self;
    
    [self presentViewController:elcPicker animated:YES completion:nil];
}


# pragma mark - 点击任意位置键盘消失
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}
//
- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    [self.view endEditing:YES];
    [_textView endEditing:YES];
    
}


- (void)cancelImagePicker
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark ELCImagePickerControllerDelegate Methods

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self cancelImagePicker];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
                
                UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
                [imageview setContentMode:UIViewContentModeScaleAspectFit];

            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                
                [images addObject:image];
                
                UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
                [imageview setContentMode:UIViewContentModeScaleAspectFit];

            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else {
            NSLog(@"Uknown asset type");
        }
    }
    [_imagePaths addObjectsFromArray:images];
    [_imageCollection reloadData];

}


- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    
}

#pragma mark - 压缩图片
- (UIImage *)compressImage:(UIImage *)imgSrc
{
    CGFloat rateOld = imgSrc.size.height/imgSrc.size.width;
    CGSize size;
    if (rateOld < 1) {
        
        size = CGSizeMake(720, rateOld*720);
    }else size = CGSizeMake(720/rateOld, 720);
    UIGraphicsBeginImageContext(size);
    CGRect rect = {{0,0}, size};
    [imgSrc drawInRect:rect];
//    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
   
    return compressedImg;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
